import { request } from '../../request/index'
import regeneratorRuntime from "../../lib/runtime/runtime"
Page({
  data: {
    tabs: [
      {
        id: 0,
        isActive: true,
        tabName: '综合'
      },
      {
        id: 1,
        isActive: false,
        tabName: '销量'
      },
      {
        id: 2,
        isActive: false,
        tabName: '价格'
      }
    ],
    goodsList: []
  },
  queryParams: {
    cid: '',
    query: '',
    pagenum: 1,
    pagesize: 10
  },
  totalPage: 1,
  /* 监听页面加载 */
  onLoad: function (options) {
    this.queryParams.cid = options.cid || '';
    this.queryParams.query = options.query || '';
    this.getGoodsList();
  },
  // 获取商品列表数据
  async getGoodsList() {
    const res = await request({
      data: this.queryParams,
      url: '/goods/search'
    });
    this.setData({
      goodsList: [ ...this.data.goodsList, ...res.data.message.goods ]
    });
    // 计算总页数
    const total = res.data.message.total;
    this.totalPage = Math.ceil(total / this.queryParams.pagesize);
    // 关闭下拉刷新窗口
    wx.stopPullDownRefresh();
  },
  // 修改tabs数组
  handTabs(e) {
    const index = e.detail;
    this.data.tabs.forEach(v => (
      v.id === index ? v.isActive = true : v.isActive = false
    ));
    this.setData({
      tabs: this.data.tabs
    });
  },
  // 滚动条触底事件
  onReachBottom() {
    // 先判断有没下一页
    if(this.queryParams.pagenum >= this.totalPage) {
      // 弹窗提示
      wx.showToast({ title: '没有下一页数据了' })
    } else {
      this.queryParams.pagenum++;
      this.getGoodsList();
    }
  },
  // 下拉刷新事件
  onPullDownRefresh() {
    this.setData({
      goodsList: []
    });
    this.queryParams.pagenum = 1;
    this.getGoodsList();
  }
})